﻿$(window).on('resize', OpenWindowSize);
OpenWindowSize();
jQuery.support.cors = true;

$.extend({
    InvokeAjax: function (obj) {
        var options = {
            data: {},
            async: true
        };
        $.extend(options, obj);

        var login_token = Cookies.get('login_token') == "" ? undefined : Cookies.get('login_token');
        if (Cookies.get('login_token') == undefined || Cookies.get('login_token') == null || Cookies.get('login_token') == "null") {
            login_token = "00000000";
        } 
       

        var _url = HttpWcf + "/" + options.url;

        $.ajax({
            url: _url,
            type: "POST",
            contentType: "application/json", headers: {
                'Token': login_token
            },
            async: options.async,
            crossDomain: true,
            data: JSON.stringify(options.data), 
            success: function (msg) {
                if (msg.Status != undefined) {
                    if (msg.Status === -6) {
                        var LoginUrl = "http://" + document.domain + ":" + window.location.port;
                        if (window.location.href != LoginUrl) {
                            window.top.location.href = LoginUrl;
                        }
                    }
                }
                if (options.callBack != undefined) {
                    options.callBack(msg);
                }
            },
            error: function (a, b, c) {
                var aa = _url;
                var err = b + ":" + a + c;
                if (options.callBack != undefined) {
                    options.callBack(err);
                }
            }
        });
    },

    layerOpen: function (obj) {
        var options = {
            id: moment().format("YYYYMMDDHHmmssSSS")
            , title: "数据操作"
            , width: "80%"
            , height: "90%"
            , url: ""
            , callback: null
            , maxmin: true
        };
        $.extend(options, obj);

        if (options.url.indexOf("?") < 0) {
            options.url += "?";
        }
        options.url += "&timestamp=" + options.id;

        var index = top.layer.open({
            id: options.id
            , maxmin: options.maxmin
            , type: 2
            , title: options.title
            , shadeClose: false
            , shade: 0.3
            , area: [options.width, options.height]
            , content: options.url
        });

        if (top.windowCache == undefined || top.windowCache == null) {
            top.windowCache = [];
        }
        top.windowCache.push({
            id: options.id,
            callback: options.callback,
            window: window,
            close: function () {
                top.layer.close(index);
            }
        });
    },

    /**
    关闭模式窗口
    */
    layerClose: function (flag) {
        if (flag == undefined) { flag = true; }
        var id = $.getUrlParamer("timestamp", "");
        var cache = top.windowCache;
        $.each(cache, function (i, e) {
            if (e.id == id) {
                if (e.callback && flag) {
                    e.callback();
                }
                if (e.close) {
                    e.close();
                }
            }
        });
    },   /**
    关闭模式窗口
    */
    DialogCallback: function (obj) {
        var id = $.getUrlParamer("timestamp", "");
        var cache = $.rootWindow().windowCache;
        $.each(cache, function (i, e) {
            if (e.id == id) {
                if (e.callback) {
                    e.callback(obj);
                }
                if (e.close) {
                    e.close();
                }
            }
        });
    },

    /**
    正则获取get参数
    */
    getUrlParamer: function (name, defaults) {
        if (defaults == undefined) defaults = "";
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return defaults;
    },

    /**
    替换全部字符
    */
    replaceAll: function (str, substr, replaceStr) {
        var re = new RegExp(substr, "g");
        str = str.replace(re, replaceStr);
        return str;
    },
    rootWindow: function () {
        return top.window;
        //var rWindow = window;
        //while (rWindow.parent != rWindow) {
        //    rWindow = rWindow.parent;
        //}
        //return rWindow;
    },


    SetAttValue: function (obj, name, defaults) {
        if (obj[name] == undefined || obj[name] == null) {
            return defaults;
        }
        if (obj[name].toString() == "") {
            return defaults;
        }
        return obj[name];
    },

    GetValue: function (id, controlType, defaultValue) {
        try {
            var type = controlType != undefined ? controlType.toUpperCase() : $("#" + id).get(0).tagName
            var result;
            switch (type) {
                case "CHECKBOX":
                    {
                        var str = ""; var ls = "";
                        $('input[name="' + id + '"]:checked').each(function () {
                            str += ls + $(this).val();
                            ls = ",";
                        });
                        result = str;
                        break;
                    }
                case "IFCHECKBOX":
                    {
                        result = $('input[name="' + id + '"]').is(":checked");
                        break;
                    }
                case "RADIO":
                    {
                        result = $("input[name='" + id + "']:checked").val();;
                        break;
                    }
                case "TEXTAREA":
                    {
                        result = $("#" + id).val();
                        break;
                    }
                case "LABEL":
                    {
                        result = $.trim($("#" + id).text());
                        break;
                    }
                case "SPAN":
                    {
                        result = $.trim($("#" + id).text());
                        break;
                    }
                case "TD":
                    {
                        result = $.trim($("#" + id).html());
                        break;
                    }
                case "UEDITOR":
                    {
                        UE.getEditor("#" + id).getContent();
                        break;
                    }
                default:
                    {
                        result = $("#" + id).val();
                        break;
                    }
            }
            if (defaultValue != undefined) {
                if (result == "") {
                    result = defaultValue;
                }
            }
            return result;
        } catch (e) {
            return "";
        }
    },
    SetValue: function (id, value, controlType) {
        try {
            if (typeof (value) != "number") {
                if (value == "") return false;
            }
            var type = controlType != undefined ? controlType.toUpperCase() : $("#" + id).get(0).tagName

            switch (type) {
                case "CHECKBOX":
                    {
                        var item = value.split(',');
                        for (var i = 0; i < item.length; i++) {
                            $("input[name='" + id + "'][value='" + item[i] + "']").attr("checked", true);
                        }
                        break;
                    }
                case "RADIO":
                    {
                        $("input[name='" + id + "'][value='" + value + "']").attr("checked", true);
                        break;
                    }
                case "SELECT":
                    {
                        $("#" + id).val(value);
                        break;
                    }
                case "LABEL":
                    {
                        $("#" + id).html(value);
                        break;
                    }
                case "SPAN":
                    {
                        $("#" + id).html(value);
                        break;
                    }
                case "TEXTAREA":
                    {
                        $("#" + id).html(value);
                        break;
                    }
                case "DIV":
                    {
                        $("#" + id).html(value);
                        break;
                    }
                case "TD":
                    {
                        $("#" + id).html(value);
                        break;
                    }
                case "UEDITOR":
                    {
                        var ue = UE.getEditor(id);
                        try {
                            ue.setContent(value);
                        }
                        catch (e) {
                        }
                        ue.addListener('ready', function (editor) {
                            ue.setContent(value);
                        });
                        break;
                    }
                default:
                    {
                        $("#" + id).val(value);
                        break;
                    }
            }
        } catch (e) {

        }
    },
    //---------------------------------------------------  
    // 日期格式化  
    // 格式 YYYY/yyyy/YY/yy 表示年份  
    // MM/M 月份  
    // W/w 星期  
    // dd/DD/d/D 日期  
    // hh/HH/h/H 时间  
    // mm/m 分钟  
    // ss/SS/s/S 秒  
    //---------------------------------------------------  
    DateFormat: function (date, formatStr) {
        //return date;
        if (date != null) {
            formatStr = formatStr.replace("yyyy-MM-dd", "YYYY-MM-DD");
            formatStr = formatStr.replace("MM-dd", "MM-DD");
            var str = moment(date, "YYYY-MM-DD HH:mm:ss SSS").format(formatStr);
            return str;
        }
    },
    JsonDateFy: function (value) {
        return value;
    },
    GetGuid: function () {
        var reslut = "";
        $.InvokeAjax("Login", "GetGuid", {}, false, function (data) {
            reslut = $.StrToJson(data).Results;
        });
        return reslut;
    },
    GetDateTime: function () {
        var reslut = "";
        $.InvokeAjax("Login", "GetDateTime", {}, false, function (data) {
            reslut = $.StrToJson(data).Results;
        });
        return reslut;
    },
    GetMd5: function (str) {
        var reslut = "";
        $.InvokeAjax("Login", "GetMd5", { PassWord: str }, false, function (data) {
            reslut = $.StrToJson(data).Results;
        });
        return reslut;
    },

    StrToJson: function (data, bool) {
        if (bool != undefined) {
            try {
                var obj = JSON.parse(data);
                if (navigator.appName == "Microsoft Internet Explorer") {
                    var IE = navigator.appVersion.split(";")[1].replace(/[ ]/g, "");
                    if (IE == "MSIE8.0" || IE == "MSIE9.0") {
                        if (typeof (obj) == "string") {
                            try {
                                obj = JSON.parse(obj);
                            }
                            catch (e) {
                            }
                        }
                    }
                }
                return obj;
            } catch (e) {
                return null;
            }
        }
        return data;
    },
    HandlebarsCompiler: function (templateID, data) {
        try {
            return Handlebars.compile($('#' + templateID).html())(data);
        }
        catch (e) {
            return "error";
        }
    },

    //获取行政区下拉菜单
    GetAreaList: function (obj) {
        $.InvokeAjax("PageService/City", "GetListEntity", { PID: obj.PID }, false, function (result) {
            var data = $.StrToJson(result).Results;
            $.fn.Select.DataBind({
                id: obj.ID, Name: "Name", Value: "ID", data: data
            });
        });
    },

    //获取行政区下拉菜单
    GetAreasList: function (obj) {
        $.InvokeAjax("PageService/City", "GetListEntity", { PID: obj.PID }, false, function (result) {
            var data = [{ ID: "", Levels: "", Name: "请选择" }];
            var results = $.StrToJson(result).Results;
            for (var x in results) {
                if (results.hasOwnProperty(x)) {
                    data.push({ ID: results[x].id, Levels: results[x].Levels, Name: results[x].text });
                }
            }
            $.fn.Select.DataBind({
                id: obj.ID, Name: "Name", Value: "ID", data: data
            });
        });
    },

    /**
        Add Common Func By JFY - Start
    */
    isNullOrEmpty: function (obj) {
        if (typeof (obj) == "undefined" || obj === "" || obj == null) {
            return true;
        }
        return false;
    },
    showConsoleLog: function (mesg) {
        if (typeof (mesg) == "undefined" || mesg === "") {
            return;
        }
        console.log(mesg);
    } 

});

function OpenWindowSize() {
    var w = $(window).width();
    if (w > 1024) {
        Cookies.set('DialogWidth', 870);
        Cookies.set('DialogHeight', 650);
    } else {
        Cookies.set('DialogWidth', w * 0.95);
        Cookies.set('DialogHeight', $(window).height() * 0.90);
    }
}